package xcmg.device.web.warehouse;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.vo.warehouse.AddWarehouseAreaLocationVO;
import xcmg.device.service.vo.warehouse.AddWarehouseAreaVO;
import xcmg.device.service.vo.warehouse.AddWarehouseVO;
import xcmg.device.service.vo.warehouse.DefaultWarehouseVO;
import xcmg.device.service.vo.warehouse.WarehouseAreaLocationVO;
import xcmg.device.service.vo.warehouse.WarehouseAreaVO;
import xcmg.device.service.vo.warehouse.WarehouseExportParamVO;
import xcmg.device.service.vo.warehouse.WarehouseSearch;
import xcmg.device.service.vo.warehouse.WarehouseStopOrOpenVO;
import xcmg.device.service.vo.warehouse.WarehouseVO;
import xcmg.device.service.warehouse.DepartmentWarehouseRelationService;
import xcmg.device.service.warehouse.WarehouseCompose;
import xcmg.device.service.warehouse.WarehouseService;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController extends BasicController {
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private DepartmentWarehouseRelationService relationService;

    @Autowired
    private WarehouseCompose warehouseCompose;

    @RequestMapping(value = "/warehouse", method = RequestMethod.POST)
    @ApiOperation(value = "增加仓库")
    @FastMappingInfo(needLogin = true, code = AuthCode.Depot.ADD)
    public ActionResult<String> warehouse(@RequestBody AddWarehouseVO addWarehouseVO) throws Exception {
        if (null == addWarehouseVO || StringUtils.isBlank(addWarehouseVO.getWarehouseCode())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(warehouseService.addWarehouse(addWarehouseVO, getOrgId()));
    }

    /**
     * @Des 根据仓库类型查询仓库列表
     * @Date 2020/11/3 19:20
     * @Author wangzhaoyu
     * @Param [warehouseType]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @RequestMapping(value = "/queryByWarehouseType", method = {RequestMethod.POST, RequestMethod.GET})
    public ActionResult<Object> warehouseByWarehouseType(String warehouseType) throws Exception {
        if (StringUtils.isEmpty(warehouseType)) {
            return ActionResultUtil.successActionResult(Collections.EMPTY_LIST);
        }
        String orgId = getOrgId();
        List<WarehouseVO> warehouses = warehouseService.getWarehouseByWarehouseType(orgId, warehouseType);
        return ActionResultUtil.successActionResult(warehouses);
    }

    @RequestMapping(value = "/area", method = RequestMethod.POST)
    @ApiOperation(value = "增加仓库区域")
    @FastMappingInfo(needLogin = true, code = AuthCode.Depot.ADD_AREA)
    public ActionResult<String> area(@RequestBody AddWarehouseAreaVO addWarehouseArea) throws Exception {
        if (null == addWarehouseArea || StringUtils.isBlank(addWarehouseArea.getAreaCode())
                || StringUtils.isBlank(addWarehouseArea.getWarehouseId())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        addWarehouseArea.setOrgId(getOrgId());
        return actionResult(warehouseService.addArea(addWarehouseArea));
    }

    @PostMapping(value = "area/stopOrOpen")
    @ApiOperation(value = "停用或启用")
    public ActionResult<String> areaStopOrOpen(@RequestBody WarehouseStopOrOpenVO stopOrOpen) {
        if (stopOrOpen == null) {
            return ActionResultUtil.errorActionResult(ErrorCode.IllegalArument);
        }
        String areaId = stopOrOpen.getAreaId();
        if (StringUtils.isEmpty(areaId)) {
            return ActionResultUtil.errorActionResult(ErrorCode.IllegalArument);
        }
        Integer stopUsing = stopOrOpen.getStopUsing();
        if (stopUsing.compareTo(1) != 0 && stopUsing.compareTo(0) != 0) {
            return ActionResultUtil.errorActionResult(ErrorCode.IllegalArument);
        }
        ErrorCode errorCode = null;
        if ("area".equals(stopOrOpen.getStorageType())) {
            //更新stopUsing字段值
            errorCode = warehouseService.areaOpenOrStopUsing(stopOrOpen.getAreaId(), stopUsing);
        } else {
            errorCode = warehouseService.warehouseOpenOrStopUsing(stopOrOpen.getAreaId(), stopUsing);
        }
        return actionResult(errorCode);

    }

    @RequestMapping(value = "/locations", method = RequestMethod.POST)
    @ApiOperation(value = "增加一批储位")
    @FastMappingInfo(needLogin = true, code = AuthCode.Depot.ADD_PLACE)
    public ActionResult<String> locations(@RequestBody AddWarehouseAreaLocationVO addWarehouseAreaLocationsVO) throws Exception {
        if (null == addWarehouseAreaLocationsVO
                || StringUtils.isBlank(addWarehouseAreaLocationsVO.getWarehouseAreaId())
                || null == addWarehouseAreaLocationsVO.getBeginRowNo()
                || null == addWarehouseAreaLocationsVO.getEndRowNo()
                || null == addWarehouseAreaLocationsVO.getFloorNum()
                || null == addWarehouseAreaLocationsVO.getColumnNum()) {
            return actionResult(ErrorCode.IllegalArument);
        }
        //结束排编号不能小于开始排编号
        if (addWarehouseAreaLocationsVO.getEndRowNo().compareTo(addWarehouseAreaLocationsVO.getBeginRowNo()) < 0) {
            return actionResult(ErrorCode.LocationEndRowNoError);
        }
        //起止排编号必须大于0
        if (addWarehouseAreaLocationsVO.getEndRowNo().intValue() <= 0
                || addWarehouseAreaLocationsVO.getBeginRowNo().intValue() <= 0) {
            return actionResult(ErrorCode.LocationBeginRowNoError);
        }
        //层数目和列数目必须大于0
        if (addWarehouseAreaLocationsVO.getFloorNum().intValue() <= 0
                || addWarehouseAreaLocationsVO.getColumnNum().intValue() <= 0) {
            return actionResult(ErrorCode.LocationFloorNumError);
        }
        //位数目必须大于0，没设置或者传0重置为1
        if (null == addWarehouseAreaLocationsVO.getLocationNum() || addWarehouseAreaLocationsVO.getLocationNum().intValue() <= 0) {
            addWarehouseAreaLocationsVO.setLocationNum(Integer.valueOf(1));
        }
        addWarehouseAreaLocationsVO.setOrgId(getOrgId());
        return actionResult(warehouseService.addWarehouseAreaLocations(addWarehouseAreaLocationsVO));
    }


    @RequestMapping(value = "/delLocations", method = RequestMethod.POST)
    @ApiOperation(value = "删除储位--根据货架编号")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> delLocations(@RequestBody AddWarehouseAreaLocationVO warehouseAreaLocationVO) throws Exception {
        if (null == warehouseAreaLocationVO ||
                StringUtils.isBlank(warehouseAreaLocationVO.getShelfNo()) ||
                StringUtils.isBlank(warehouseAreaLocationVO.getAreaNo()) ||
                StringUtils.isBlank(warehouseAreaLocationVO.getWarehouseCode()) ||
                StringUtils.isBlank(warehouseAreaLocationVO.getWarehouseAreaId())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        warehouseAreaLocationVO.setOrgId(getOrgId());
        return actionResult(warehouseService.delWarehouseAreaLocations(warehouseAreaLocationVO));
    }

    @RequestMapping(value = "/listWarehouses", method = RequestMethod.GET)
    @ApiOperation(value = "分页查询仓库，查询条件为企业标识，选填")
    @FastMappingInfo(needLogin = true)
    public ActionResult<PageInfo<WarehouseVO>> listWarehouses(int pageNum, int pageSize, String warehouseCode, String description, String keyWords, String billNos, String purchaseOrgName, String warehouseType) throws Exception {
        PageCommonVO<WarehouseVO> pageCommonVO = warehouseService.listWarehouses(pageNum, pageSize, warehouseCode, description, getOrgId(), keyWords, billNos, purchaseOrgName, warehouseType, null);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ApiOperation(value = "仓库导出功能")
    @FastMappingInfo(needLogin = true)
    public void warehousesExportOut(WarehouseExportParamVO warehouseExportParamVO) throws Exception {
        String orgId = getOrgId();
        String warehouseCode = warehouseExportParamVO.getWarehouseCode();
        String description = warehouseExportParamVO.getDescription();
        String keyWords = warehouseExportParamVO.getKeyWords();
        String billNos = warehouseExportParamVO.getBillNos();
        String purchaseOrgName = warehouseExportParamVO.getPurchaseOrgName();
        String warehouseType = warehouseExportParamVO.getWarehouseType();
        warehouseService.exportWarehouses(warehouseCode, description, orgId, keyWords, billNos, purchaseOrgName, warehouseType);
    }

    /**
     * 从listWarehouses接口copy出来的接口，原接口调用处较多，暂不改动
     *
     * @param condition
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listByFilters", method = RequestMethod.POST)
    @ApiOperation(value = "分页查询仓库，带条件")
    @FastMappingInfo(needLogin = true)
    public ActionResult<PageInfo<WarehouseVO>> listByFilters(@RequestBody SearchCommonVO<WarehouseSearch> condition) throws Exception {
        WarehouseSearch filters = condition.getFilters();
        if (null == filters) {
            filters = new WarehouseSearch();
            condition.setFilters(filters);
        }
        filters.setOrgId(getOrgId());
        PageCommonVO<WarehouseVO> pageCommonVO = warehouseService.listWarehouses2(condition.getPageNum(), condition.getPageSize(), filters);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "listByFilters/inventoryPermit", method = RequestMethod.POST)
    @ApiOperation(value = "分页查询仓库，根据仓库库存权限配置过滤")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listByFiltersInventoryPermit(@RequestBody SearchCommonVO<WarehouseSearch> condition) throws Exception {
        WarehouseSearch filters = condition.getFilters();
        if (null == filters) {
            filters = new WarehouseSearch();
            condition.setFilters(filters);
        }
        String orgId = getOrgId();
        String departmentId = getDeptId();
        PageCommonVO<Object> pageCommonVO = warehouseService.listInventoryPermit(condition.getPageNum(), condition.getPageSize(),
                filters.getWarehouseCode(), filters.getDescription(), orgId, departmentId);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "listByFilters/permit", method = RequestMethod.POST)
    @ApiOperation(value = "分页查询仓库，带条件,带仓库权限配置")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listByFiltersPermit(@RequestBody SearchCommonVO<WarehouseSearch> condition) throws Exception {
        WarehouseSearch filters = condition.getFilters();
        if (null == filters) {
            filters = new WarehouseSearch();
            condition.setFilters(filters);
        }
        String orgId = getOrgId();
        String departmentId = getDeptId();
        PageCommonVO<Object> pageCommonVO = warehouseService.listWarehousesPermit(condition.getPageNum(), condition.getPageSize(),
                filters.getWarehouseCode(), filters.getDescription(), orgId, departmentId, filters.getStopUsing());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "listByFilters/majorPermit", method = RequestMethod.POST)
    @ApiOperation(value = "分页查询仓库，带条件,主库去权限配置")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listByFiltersMajorPermit(@RequestBody SearchCommonVO<WarehouseSearch> condition) throws Exception {
        WarehouseSearch filters = condition.getFilters();
        if (null == filters) {
            filters = new WarehouseSearch();
            condition.setFilters(filters);
        }
        String orgId = getOrgId();
        String departmentId = getDeptId();
        PageCommonVO<Object> pageCommonVO = warehouseService.listWarehousesMajorPermit(condition.getPageNum(), condition.getPageSize(),
                filters.getWarehouseCode(), filters.getDescription(), orgId, departmentId, filters.getStopUsing());
        return actionValueResult(pageCommonVO.getPageInfo());
    }


    @RequestMapping(value = "/listNoBarcode", method = RequestMethod.GET)
    @ApiOperation(value = "分页查询仓库，查询条件为企业标识，选填")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listNoBarcode(int pageNum, int pageSize, String warehouseCode, String description) throws Exception {
        PageCommonVO<Object> pageCommonVO = warehouseService.listNoBarcode(pageNum, pageSize, getOrgId(), warehouseCode, description);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listAreas", method = RequestMethod.GET)
    @ApiOperation(value = "分页查询仓库区域，查询条件为仓库编号，选填")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listAreas(int pageNum, int pageSize, String warehouseId) {
        PageCommonVO<Object> pageCommonVO = warehouseService.listAreas(pageNum, pageSize, warehouseId);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/moreAreaList", method = RequestMethod.GET)
    @ApiOperation(value = "查询多库区")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> moreAreaList(String warehouseIds) {
        List<WarehouseAreaVO> results = warehouseService.moreAreaList(warehouseIds);
        return actionValueResult(results);
    }

    @RequestMapping(value = "/listLocations", method = RequestMethod.GET)
    @ApiOperation(value = "分页查询储位，查询条件为仓库区域编号，选填")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> listLocations(int pageNum, int pageSize, String areaId) {
        PageCommonVO<Object> pageCommonVO = warehouseService.listLocations(pageNum, pageSize, areaId);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/updateLocationDesc", method = RequestMethod.POST)
    @ApiOperation(value = "修改储位描述")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> updateLocationDesc(@RequestBody WarehouseAreaLocationVO warehouseAreaLocationVO) {
        ErrorCode code = warehouseService.updateLocationDesc(warehouseAreaLocationVO);
        return actionResult(code);
    }

    @RequestMapping(value = "/listShlefNos", method = RequestMethod.GET)
    @ApiOperation(value = "分页查询仓库下的货架编号")
    public ActionResult<Object> listShlefNos(int pageNum, int pageSize, String areaId) {
        PageCommonVO<Object> pageCommonVO = warehouseService.listShlefNos(pageNum, pageSize, areaId);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/removeWarehouse", method = RequestMethod.POST)
    @ApiOperation(value = "删除仓库")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> removeWarehouse(@RequestBody String warehouseId) {
        if (StringUtils.isBlank(warehouseId)) {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(warehouseService.deleteWarehouse(warehouseId));
    }

    @RequestMapping(value = "/removeArea", method = RequestMethod.POST)
    @ApiOperation(value = "删仓库区域")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> removeArea(@RequestBody String warehouseAreaId) {
        if (StringUtils.isBlank(warehouseAreaId)) {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(warehouseService.deleteArea(warehouseAreaId));
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "修改")
    @FastMappingInfo(needLogin = true)
    public ActionResult<String> update(@RequestBody WarehouseVO warehouseVO) {
        if (null == warehouseVO || StringUtils.isBlank(warehouseVO.getId()) || StringUtils.isBlank(warehouseVO.getDescription())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            warehouseVO.setOrgId(getOrgId());
            warehouseService.update(warehouseVO);
        } catch (Exception e) {
            return new ActionResult<>(ErrorCode.Failure.getCode(), e.getMessage());
        }
        return actionResult(ErrorCode.Success);
    }

    @RequestMapping(value = "/findAreaCodeList", method = RequestMethod.GET)
    @ApiOperation(value = "根据仓库编码查找库区")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> findAreaCodeList(String warehouseCode) throws Exception {
        PageCommonVO<Object> pageCommonVO = warehouseService.findAreaCodeList(warehouseCode, getOrgId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/findAbleAreaCodeList", method = RequestMethod.GET)
    @ApiOperation(value = "根据仓库编码查找库区")
    @FastMappingInfo(needLogin = true)
    public ActionResult<Object> findAbleAreaCodeList(String warehouseCode) throws Exception {
        PageCommonVO<Object> pageCommonVO = warehouseService.findAbleAreaCodeList(warehouseCode, getOrgId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/areaCodeListPage", method = RequestMethod.GET)
    @ApiOperation(value = "根据仓库编码查找库区")
    public ActionResult<Object> areaCodeListPage(int pageNum, int pageSize, String warehouseCode, Integer stopUsingControl) throws Exception {
        //该接口调用的地方比较多，所以直接加一个参数stopUsingControl，默认为1表示受停用/启用控制，只查询启用的库区，如果需要不受停/启用控制，直接让前端传值为0表示不受控制
        stopUsingControl = stopUsingControl == null ? 1 : stopUsingControl;
        PageCommonVO<Object> pageCommonVO = warehouseService.areaCodeListPage(pageNum, pageSize, warehouseCode, getOrgId(), stopUsingControl);
        return actionValueResult(pageCommonVO.getPageInfo());
    }


    @GetMapping("/queryDefaultWarehouseVO")
    @ApiOperation(value = "查询企业的默认仓库库区储位")
    public ActionResult<DefaultWarehouseVO> queryDefaultWarehouseVO(@RequestParam(value = "orgId", required = false) String orgId) throws Exception {
        if (StringUtils.isBlank(orgId)) {
            orgId = getOrgId();
        }
        DefaultWarehouseVO vo = warehouseCompose.queryDefaultWarehouseVO(orgId);
        return actionValueResult(vo);
    }

}
